package com.qianfeng.android.baoman.util;

import android.text.TextUtils;
import android.util.Log;

import com.qianfeng.android.baoman.Constants;
import com.qianfeng.android.baoman.model.Other;
import com.qianfeng.android.baoman.task.BindLoginTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Android_Studio on 2015/3/16.
 * User:Maxiaoyu
 * Date:2015/3/16
 * Email:731436452@qq.com
 */
public class LoginHelper {

    public static Other login_v2(String paramString1, String paramString2) {
//        String str1 = ah.getLoginUrl_v2();
        String str1 = "http://api.ibaozou.com/api/v2/login";
        Log.i("test", "登录 url =  " + str1);
        HashMap localHashMap = new HashMap();
        localHashMap.put("username", paramString1);
        localHashMap.put("password", paramString2);
        localHashMap.put("client_id", "10230158");
        localHashMap.put("timestamp", Long.toString(System.currentTimeMillis()));
        ArrayList localArrayList = new ArrayList();
        localArrayList.add("client_id");
        localArrayList.add("username");
        localArrayList.add("password");
        localArrayList.add("timestamp");
        String str2 = getMD5Sign(localHashMap, localArrayList);
        Other localbh = null;
        if (TextUtils.isEmpty(str2)) {
            localbh = null;
        }
//        do {
//            return localbh;
        localHashMap.put("sign", str2);
        doPost(str1, localHashMap);


//        String str3 = doPost(str1, localHashMap);
        /*Log.i("test", "登录 result =  " + str3);
        localbh = parseUserJson(str3);
//        } while ((localbh == null) || (localbh.isError()));

        localbh.setPassword(paramString2);
        fillUserDetailInfo(localbh);
        return localbh;*/
        return null;
    }


    public static String getMD5Sign(Map<String, String> paramMap, List<String> paramList) {
        StringBuilder localStringBuilder = new StringBuilder();
        if ((paramMap == null) || (paramList == null)) {
            return "";
        }
        Collections.sort(paramList);
        for (int i = 0; i < paramList.size(); i++) {
            String str1 = null;
          /*  if (i >= paramList.size()) {
                localStringBuilder.append("18a75cf12dff8cf6e17550e25c860839");
                str1 = localStringBuilder.toString();
                Log.i("Common", "sign = " + str1);
                String str2 = null;
                try {
                    str2 = URLEncoder.encode(str1, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return Constants.get32MD5(str2);
            }*/
          /*  try {
                String str2 = URLEncoder.encode(str1, "utf-8");
                return Constants.get32MD5(str2);
            } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
                localUnsupportedEncodingException.printStackTrace();
            }*/
            if (paramMap.containsKey(paramList.get(i))) {
                String s = paramList.get(i);
                String s1 = paramMap.get(s);
                localStringBuilder.append(s + "=" + s1);
            }
        }
        localStringBuilder.append("18a75cf12dff8cf6e17550e25c860839");
        String str1 = localStringBuilder.toString();
        Log.i("Common", "sign = " + str1);
        String str2 = null;
        try {
            str2 = URLEncoder.encode(str1, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return Constants.get32MD5(str2);


//        return "";
    }


    public static String doPost(final String paramString, final Map<String, String> paramMap) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpTool.post(paramString, (HashMap<String, String>) paramMap);
            }
        }).start();

      /*  DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
        HttpPost localHttpPost = new HttpPost(paramString);
        ArrayList localArrayList = new ArrayList();
        Iterator localIterator = null;
        if (paramMap != null) {
            localIterator = paramMap.keySet().iterator();
        }

        while (localIterator.hasNext()) {
            String str2 = (String) localIterator.next();
            localArrayList.add(new BasicNameValuePair(str2, (String) paramMap.get(str2)));
        }

        try {
            localHttpPost.setEntity(new UrlEncodedFormEntity(localArrayList, "utf-8"));

            HttpResponse execute = localDefaultHttpClient.execute(localHttpPost);
            HttpEntity entity = execute.getEntity();
//                EntityUtils.toString("");
            String s = EntityUtils.toString(entity);
            InputStream content = entity.getContent();
            if (s != null) {
                System.out.println("content = " + s);
            }

//                String str1 = a(localDefaultHttpClient.execute(localHttpPost).getEntity().getContent());
            String str1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            return str1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
*/
       /* for (int i=0;i<paramMap.size() ;i++ ) {
            if (!localIterator.hasNext()) {
            }
            try {
                localHttpPost.setEntity(new UrlEncodedFormEntity(localArrayList, "utf-8"));

                HttpResponse execute = localDefaultHttpClient.execute(localHttpPost);
                HttpEntity entity = execute.getEntity();
//                EntityUtils.toString("");

                InputStream content = entity.getContent();


//                String str1 = a(localDefaultHttpClient.execute(localHttpPost).getEntity().getContent());
                String str1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
                return str1;
            } catch (Exception localException) {

                localException.printStackTrace();
            }
            String str2 = (String) localIterator.next();
            localArrayList.add(new BasicNameValuePair(str2, (String) paramMap.get(str2)));
        }*/
        return null;
    }

    private static String a(String paramString)
            throws IllegalStateException, IOException {
        return parseStringFromEntity(getStream(paramString));
    }


    public static InputStream getStream(String paramString)
            throws IllegalStateException, IOException {
        try {
            BasicHttpParams localBasicHttpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 8000);
            HttpConnectionParams.setSoTimeout(localBasicHttpParams, 8000);
            DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(localBasicHttpParams);
            HttpGet localHttpGet = new HttpGet(paramString);
            HttpResponse localHttpResponse = localDefaultHttpClient.execute(localHttpGet);
            if (localHttpResponse == null) {
                localHttpResponse = localDefaultHttpClient.execute(localHttpGet);
                Log.v("test", "resonse ------------ " + localHttpResponse);
            }
            InputStream localInputStream = localHttpResponse.getEntity().getContent();
            return localInputStream;
        } catch (Exception localException) {
            localException.printStackTrace();
        }
        return null;
    }

    public static String parseStringFromEntity(InputStream paramInputStream)
            throws IllegalStateException, IOException, OutOfMemoryError {
        if (paramInputStream == null) {
            return null;
        }
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(paramInputStream));
        StringBuffer localStringBuffer = new StringBuffer();
        for (; ; ) {
            String str = localBufferedReader.readLine();
            if (str == null) {
                return localStringBuffer.toString();
            }
            localStringBuffer.append(str);
        }
    }


    public static Other parseUserJson(String paramString) {
        Other other = null;
        if (TextUtils.isEmpty(paramString)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(paramString);
            other = new Other();
            other.parseJSON(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return other;
      /*  if (TextUtils.isEmpty(paramString)) {
            return null;
        }
        try
        {
        Other localbh = null;
            JSONObject localJSONObject = new JSONObject(paramString);
//            localbh = new bh();
            localbh=new Other();
            if (paramString.contains("error"))
            {
//                localbh.setError(true);
//                localbh.setErrerDetail(localJSONObject.getString("detail"));
//                localbh.setErrerId(localJSONObject.getInt("error"));
            }
            else if (paramString.contains("user_id"))
            {
                localbh.setUid(localJSONObject.getInt("user_id"));
                localbh.setUsername(localJSONObject.getString("user_name"));
                localbh.setFaceUrl(localJSONObject.getString("user_avatar"));
                localbh.setToken(localJSONObject.getString("access_token"));
                localbh.setError(false);
            }
        }
        catch (JSONException localJSONException)
        {
            localJSONException.printStackTrace();
            localbh = null;
        }
        return localbh; */
    }

    public static void fillUserDetailInfo(Other parambh) {
        parseUserDetailJson(doGet(getUserDetailUrl(parambh.getId())), parambh);
    }

    public static Other parseUserDetailJson(String paramString, Other parambh) {
        if (TextUtils.isEmpty(paramString)) {
            return parambh;
        }
        try {
            JSONObject localJSONObject = new JSONObject(paramString);
            parambh.setFriends_count(localJSONObject.getInt("friends_count"));
            parambh.setSalary(localJSONObject.getInt("salary"));
            parambh.setArticles_count(localJSONObject.getInt("articles_count"));
            parambh.setPublic_articles_count(localJSONObject.getInt("public_articles_count"));
            parambh.setFollowers_count(localJSONObject.getInt("followers_count"));
            parambh.setActive(localJSONObject.getBoolean("active"));
            parambh.setEmail(localJSONObject.getString("email"));
            return parambh;
        } catch (JSONException localJSONException) {
            localJSONException.printStackTrace();
        }
        return parambh;
    }

    public static String doGet(String paramString) {
        try {
            String str = a(paramString);
            return str;
        } catch (IllegalStateException localIllegalStateException) {
            localIllegalStateException.printStackTrace();
            return null;
        } catch (IOException localIOException) {
            localIOException.printStackTrace();
            return null;
        } catch (OutOfMemoryError localOutOfMemoryError) {
            localOutOfMemoryError.printStackTrace();
            return null;
        } catch (Exception localException) {
            localException.printStackTrace();
        }
        return null;
    }

    public static String getUserDetailUrl(int paramInt) {
        return "http://api.ibaozou.com/users/" + paramInt + ".app";
    }


    public static void bindUserToken(String paramString1, String paramString2, String paramString3) {
        HashMap localHashMap = new HashMap();
        String str1 = Long.toString(System.currentTimeMillis() / 1000L);
        String str2 = null;
        if (!TextUtils.isEmpty(paramString1)) {
            str2 = "client_id=10230158installation=" + paramString2 + "timestamp=" + str1 + "18a75cf12dff8cf6e17550e25c860839";
        }
        String str3 = null;
        try {
            String str5 = URLEncoder.encode(str2, "utf-8");
            str3 = str5;
        } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
            localUnsupportedEncodingException.printStackTrace();
        }
        String str4 = Constants.get32MD5(str3);
        localHashMap.put("client_id", "10230158");
        localHashMap.put("type", "1");
        localHashMap.put("from", "ixintui");
        localHashMap.put("sign", str4);
        localHashMap.put("timestamp", str1);
        localHashMap.put("installation", paramString2);
//        a.i("HttpDataCommon", "bindUserToken:uid=" + paramString1);
//        a.i("HttpDataCommon", "bindUserToken:MD5Sign=" + str4);
//        a.i("HttpDataCommon", "installation:" + paramString2);
//        a.i("HttpDataCommon", "access_token:" + paramString3);
//        a.i("HttpDataCommon", "client_id  ：10230158;installation:" + paramString2 + ";timestamp:" + str1 + ";sign:" + str4);


        str2 = "access_token=" + paramString3 + "client_id=" + 10230158 + "installation=" + paramString2 + "timestamp=" + str1 + "user_id=" + paramString1 + "18a75cf12dff8cf6e17550e25c860839";
        localHashMap.put("user_id", paramString1);
        localHashMap.put("access_token", paramString3);
        BindLoginTask task = new BindLoginTask();
        task.execute(localHashMap);

        return;
    }
}
